/**
 *
 */
package com.elcom.emocbc.cbm;

import com.elcom.emocbc.common.ipc.cbcgwmessage.CBM_SUBMIT_RESP;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;

import com.elcom.emocbc.db.CellBroadcastDAO;
import com.elcom.emocbc.util.GeneratorSeq;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author tiamo114
 *
 */
public class BroadcastJob implements Job {

    private final Logger logger = LoggerFactory.getLogger(BroadcastJob.class);
    private Scheduler schedule = null;
    private BroadcastDTO broadcast = null;
    private CellBroadcastDAO dao = null;

    /**
     *
     */
    public BroadcastJob() {
        dao = new CellBroadcastDAO();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.quartz.Job#execute(org.quartz.JobExecutionContext)
     */
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        broadcast = BroadcastDTO.class.cast(context.getMergedJobDataMap().get("broadcast"));
        schedule = Scheduler.class.cast(context.getMergedJobDataMap().get("schedule"));
        String job_name = (String) context.getMergedJobDataMap().get("job_name");
        String job_group = (String) context.getMergedJobDataMap().get("job_group");

        List<MenuItemDTO> listMenu = dao.getListMenuItem(broadcast.getTopicID(), broadcast.getProgramID());
        String display = dao.getDisplayContent(broadcast.getProgramID());
        logger.debug("Zone {} - Time {} - Broadcasting subcontent: {}", broadcast.getZone(), broadcast.getStartTime(), display);

        // Create an array containing the elements in a list
        MenuItemDTO[] menu = new MenuItemDTO[listMenu.size()];
        for (int i = 0; i < menu.length; i++) {
            menu[i] = listMenu.get(i);
        }

        try {
            int messageID = GeneratorSeq.getNextSeq();
            CBM_SUBMIT_RESP rs = CellBroadcastService.generateCBMStructFile(menu, display, messageID, broadcast);
            int errorCode = rs.getErrorCode();
            dao.insertBroadcastHist(broadcast, display, errorCode);

            logger.info("Zone {} - Time {} - Finish broadcast for: {}", broadcast.getZone(), broadcast.getStartTime(), broadcast.toString());
            dao.updateStateBroadcast(broadcast, CellBroadcastService.NORMAL);

            try {
                schedule.deleteJob(job_name, job_group);
            } catch (SchedulerException e) {
                logger.error("", e);
            }
        } catch (Exception e) {
            logger.error("", e);
        }

    }
}
